package com.webserver.servlet;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.Arrays;

public class RegServlet extends HttpServlet{
    public void service(HttpRequest request, HttpResponse response){
        String username = request.getParameters("username");
        String password = request.getParameters("password");
        String nickname = request.getParameters("nickname");
        String agestr = request.getParameters("age");

        System.out.println("username:"+username);
        System.out.println("password:"+password);
        System.out.println("nickname:"+nickname);
        System.out.println("agestr:"+agestr);

        if (username==null||password==null||nickname==null||agestr==null||!agestr.matches("\\d+")){
            File file = new File("./webapps/myweb/reg_info_error.html");
            response.setEntity(file);
            return;
        }

        int age = Integer.parseInt(agestr);
        try(RandomAccessFile raf = new RandomAccessFile("./user.dat","rw")) {
            for (int i =0;i<raf.length()/100;i++){
                raf.seek(i*100);
                byte[]data = new byte[32];
                raf.read(data);
                String name = new String(data,"utf-8").trim();
                if (name.equals(username)) {
                    File file = new File("./webapps/myweb/have_user.html");
                    response.setEntity(file);
                    return;
                }
            }

            raf.seek(raf.length());
            byte[]data = username.getBytes("utf-8");
            data = Arrays.copyOf(data,32);
            raf.write(data);

            data = password.getBytes("utf-8");
            data = Arrays.copyOf(data,32);
            raf.write(data);

            data = nickname.getBytes("utf-8");
            data = Arrays.copyOf(data,32);
            raf.write(data);

            raf.writeInt(age);

            File file = new File("./webapps/myweb/reg_success.html");
            response.setEntity(file);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
